﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using FinPlusWCFConnData;
using FinPlusCommon;
using log = Logger.Logger;
using u = FinPlusUtility.Utility;

namespace FinPlusWPFControls
{
    public sealed class FinPlusMenuItem:FinPlusControl
    {
        public override string Id { get; set; }
        public override string[] States { get { return new string[] { }; } }
        public override string[] TestStates { get { return new string[] {  }; } }
        public override IFinPlusFunctions Model { get { return null; } }
        public override bool IsValid { get; set; }
        public override string ModelTest{get { return string.Empty; }}

        private enum DockControls { FinPlusMenuItem, Exception }
        public enum Action { Edit, Clone, Copy, Print, None, Default }
        public MenuItem MenuItem { get; private set; }

        private object _placement;
        private readonly string _parms, _childPath, _action;
        private FinPlusWindow _window;
        private static ResourceDictionary _images;

        //construct
        public FinPlusMenuItem(string header, string icon, string action, string parms)
        {
            MenuItem = new MenuItem();
            if (!header.Equals(""))
                MenuItem.Header = header;
            MenuItem.Click += MenuItem_Click;
            AddIcon(icon);
            _parms = parms;
            _action = action;
            _childPath = u.GetAssemblyPath(Assembly.GetExecutingAssembly()) + "FinPlusChildClients\\";
            IsValid = true;
        }
   
        //common control interface 
        public override void Dock(object control, string dock)
        {
            try
            {
                switch (u.EnumTryParse<DockControls>(control.GetType().Name, DockControls.Exception))
                {
                    case DockControls.FinPlusMenuItem: AddMenuItem((FinPlusMenuItem)control); break;
                    case DockControls.Exception: throw new Exception();
                }
            }
            catch (Exception e)
            {
                IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        public override void Initialise()
        {

        }

        public override void CommandRouter(IFinPlusFunction func)
        {
            try
            {
                CaptureCommand(func);

                switch ((Commands)Enum.Parse(typeof(Commands), func.Name, true))
                {
                    case Commands.ExecuteAction: ExecuteAction(); break;
                    default: throw new Exception(string.Format("event not recognised {0}", func.Name));
                }
            }
            catch (Exception e)
            {
                IsValid = log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        public override void Dispose()
        {
            
        }

        //private
        private void ExecuteAction()
        {
            if (_placement == null) _placement = GetPlacementTarget();

            if(_window == null) _window = ControlSearch.FindVisualParent<FinPlusWindow>((DataGrid)_placement);

            switch (u.EnumTryParse<Action>(_action, Action.Default))
            {
                case Action.Clone: FinPlusWindow.Open(GetFunc().Clone(-1), "FuncEdit", Env); break;
                case Action.Edit: FinPlusWindow.Open(GetFunc(), "FuncEdit", Env); break;
                case Action.Copy: ApplicationCommands.Copy.Execute(null, (DataGrid)_placement); break;
                case Action.Print: new PrintDialog().PrintVisual((DataGrid)_placement, "Printing"); break;
                case Action.None: break;
                case Action.Default: OpenProcess(); break;
            }
        }

        private object GetPlacementTarget()
        {
           var res = MenuItem.Parent;
           do
           {
               if(res.GetType().Equals(typeof(MenuItem)))
                   res = ((MenuItem)res).Parent;
               else
                   break;
           }
           while(true);

           return ((ContextMenu)res).PlacementTarget;
        }

        private IFinPlusFunction GetFunc()
        {
            return ((IFinPlusFuncDynamic)((DataGrid)_placement).CurrentItem).ToFunction();
        }

        private void AddMenuItem(FinPlusMenuItem menuItem)
        {
            MenuItem.Items.Add(menuItem.MenuItem);
        }

        private void AddIcon(string icon)
        {
            if (_images == null)
                _images = new ResourceDictionary { Source = new Uri("pack://application:,,,/FinPlusWPFControls;component/Resource.Images.xaml", UriKind.RelativeOrAbsolute) };

            if (!string.IsNullOrEmpty(icon))
                MenuItem.Icon =  new Image { Source = (BitmapImage)_images[icon] };
        }

        private void OpenProcess()
        {
            FinPlusWindow.OpenProcess(string.Format("{0}{1}", _childPath, _action), _action, _window.Guid, GetFunc().Replace(_parms));
        }

        //cmds
        private new enum Commands { ExecuteAction }

        //events
        private void MenuItem_Click(object sender, System.Windows.RoutedEventArgs a) {CommandRouter(new Function(Commands.ExecuteAction.ToString(), Id, User));}
    }
}


























































































//Copyright2013<jnrton>AllRightsReserved 
//Contact j.nrton@finpus